package org.jcodetools.lang;

import java.math.BigDecimal;
import java.util.Random;

/**
 * Created by Administrator on 2017/6/9/009.
 */
public class MathUtils {
    /**
     * 在指定范围内生成随机整数
     *
     * @param min 最小值
     * @param max 最大值
     * @return 返回随机数
     */
    public Integer randomIntBetween(int min, int max) {
        Random random = new Random();
        int randomInt = random.nextInt(max) % (max - min + 1) + min;
        return randomInt;
    }

    /**
     * 两个整数相除，并保留指定的小数位数
     *
     * @param val     被除数
     * @param divisor 除数
     * @param scale   精确的小数位数
     * @return 返回计算后double结果
     */
    public static double division(int val, int divisor, int scale) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.divide(new BigDecimal(divisor), scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static double division(long val, long divisor, int scale) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.divide(new BigDecimal(divisor), scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static double division(double val, int divisor, int scale) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.divide(new BigDecimal(divisor), scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static int multiply(int val, double multiplicand) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.multiply(new BigDecimal(multiplicand)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
    }

    public static double multiply(double val, double multiplicand) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.multiply(new BigDecimal(multiplicand)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static int multiply(double val, int multiplicand) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.multiply(new BigDecimal(multiplicand)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
    }

    public static long multiply(long val, double multiplicand) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.multiply(new BigDecimal(multiplicand)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
    }

    public static long multiply(double val, long multiplicand) {
        BigDecimal valBigDecimal = new BigDecimal(val);
        return valBigDecimal.multiply(new BigDecimal(multiplicand)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
    }

}
